<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>订单详情🔍</title>
    <!-- 引入WeUI CSS -->
    <link rel="stylesheet" href="./weui/weui.min.css">
    <style>
        /* 全局样式 */
        body {
            background-color: #f5f5f5;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            min-height: 100vh;
            padding-bottom: 20px;
        }
        
        .page-container {
            max-width: 800px;
            margin: 0 auto;
            padding: 15px;
        }
        
        /* 头部样式 */
        .header {
            text-align: center;
            margin-bottom: 25px;
            padding: 25px 0 15px;
            position: relative;
        }
        
        .header::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 60px;
            height: 4px;
            background: linear-gradient(to right, #07C160, #10a5c5);
            border-radius: 2px;
        }
        
        .header-title {
            font-size: 26px;
            color: #333;
            font-weight: 600;
            margin-bottom: 10px;
            letter-spacing: 1px;
        }
        
        /* 筛选区域样式 */
        .filter-section {
            background-color: white;
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 20px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
        }
        
        .filter-row {
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }
        
        .filter-group {
            flex: 1;
            min-width: 200px;
        }
        
        .filter-label {
            font-size: 14px;
            color: #666;
            font-weight: 500;
            margin-bottom: 5px;
            display: block;
        }
        
        .weui-select {
            width: 100%;
            height: 40px;
            line-height: 40px;
            border: 1px solid #e5e5e5;
            border-radius: 8px;
            padding: 0 15px;
            font-size: 14px;
            background-color: white;
            box-sizing: border-box;
        }
        
        /* 下拉选择区域样式 */
        .dropdown-container {
            background-color: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
            position: relative;
        }
        
        .dropdown-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 15px;
            border: 1px solid #e5e5e5;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .dropdown-header:hover {
            border-color: #07C160;
        }
        
        .dropdown-header.active {
            border-color: #07C160;
            background-color: rgba(7, 193, 96, 0.05);
        }
        
        .dropdown-title {
            font-size: 16px;
            font-weight: 600;
            color: #333;
        }
        
        .dropdown-arrow {
            transition: transform 0.3s ease;
            color: #666;
        }
        
        .dropdown-arrow.open {
            transform: rotate(180deg);
        }
        
        .selected-order {
            margin-top: 10px;
            padding: 10px 15px;
            background-color: #f8f8f8;
            border-radius: 6px;
            font-size: 16px;
            color: #333;
            font-weight: 500;
            text-align: center;
        }
        
        .selected-order .order-number {
            font-weight: 600;
            color: #07C160;
        }
        
        .dropdown-list {
            position: absolute;
            top: 100%;
            left: 20px;
            right: 20px;
            background-color: white;
            border: 1px solid #e5e5e5;
            border-radius: 8px;
            max-height: 300px;
            overflow-y: auto;
            z-index: 10;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            display: none;
        }
        
        .dropdown-list.open {
            display: block;
        }
        
        /* 搜索框样式 */
        .search-container {
            padding: 15px;
            border-bottom: 1px solid #f0f0f0;
            position: sticky;
            top: 0;
            background-color: white;
            z-index: 5;
        }
        
        .search-input {
            width: 100%;
            height: 40px;
            border: 1px solid #e5e5e5;
            border-radius: 8px;
            padding: 0 15px;
            font-size: 14px;
            box-sizing: border-box;
            transition: all 0.3s ease;
        }
        
        .search-input:focus {
            border-color: #07C160;
            outline: none;
            box-shadow: 0 0 0 2px rgba(7, 193, 96, 0.1);
        }
        
        .search-input::placeholder {
            color: #999;
        }
        
        .order-item {
            padding: 15px;
            border-bottom: 1px solid #f0f0f0;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .order-item:last-child {
            border-bottom: none;
        }
        
        .order-item:hover {
            background-color: rgba(7, 193, 96, 0.05);
        }
        
        .order-item.active {
            background-color: rgba(7, 193, 96, 0.1);
            border-left: 3px solid #07C160;
        }
        
        .order-number {
            font-weight: 600;
            color: #333;
            margin-bottom: 5px;
        }
        
        .order-meta {
            display: flex;
            gap: 15px;
            font-size: 12px;
            color: #666;
        }
        
        .order-status {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 4px;
            font-size: 11px;
            font-weight: 500;
        }
        
        .status-completed {
            background-color: #32CD32;
            color: white;
        }
        
        .status-pending {
            background-color: #FFD700;
            color: #333;
        }
        
        .load-more {
            text-align: center;
            padding: 15px;
            color: #07C160;
            cursor: pointer;
            font-weight: 500;
            display: none;
        }
        
        .loading-indicator {
            text-align: center;
            padding: 10px;
            color: #999;
            font-size: 14px;
            display: none;
        }
        
        /* 没有更多数据提示 */
        .no-more-data {
            text-align: center;
            padding: 15px;
            color: #999;
            font-size: 14px;
            border-top: 1px solid #f0f0f0;
            display: none;
        }
        
        /* 订单详情样式 */
        .order-detail-container {
            background-color: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 15px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
        }
        
        .detail-section {
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .detail-section:last-child {
            border-bottom: none;
        }
        
        .section-title {
            font-size: 18px;
            font-weight: 600;
            color: #333;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
        }
        
        .section-title::before {
            content: '';
            display: inline-block;
            width: 4px;
            height: 16px;
            background: linear-gradient(to bottom, #07C160, #10a5c5);
            border-radius: 2px;
            margin-right: 8px;
        }
        
        .detail-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 15px;
        }
        
        .detail-item {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px dashed #f0f0f0;
        }
        
        .detail-item:last-child {
            border-bottom: none;
        }
        
        .detail-label {
            color: #666;
            font-size: 14px;
        }
        
        .detail-value {
            color: #333;
            font-weight: 500;
            text-align: right;
            max-width: 60%;
            word-break: break-word;
        }
        
        /* 图片预览容器 */
        .photo-preview-container {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            margin-top: 10px;
        }
        
        .photo-preview-item {
            width: calc(33.333% - 8px);
            border: 1px solid #eee;
            border-radius: 6px;
            overflow: hidden;
        }
        
        .photo-preview-item img {
            width: 100%;
            height: 80px;
            object-fit: contain;
            cursor: pointer;
        }
        
        /* 操作按钮区域 */
        .order-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
        }
        
        .end-btn {
            background: linear-gradient(to right, #07C160, #10a5c5);
            color: white;
            border: none;
            border-radius: 6px;
            padding: 10px 20px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .edit-btn {
            background: linear-gradient(to right, #FFA500, #FF8C00);
            color: white;
            border: none;
            border-radius: 6px;
            padding: 10px 20px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .end-btn:hover, .edit-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
        }
        
        .end-btn:active, .edit-btn:active {
            transform: translateY(0);
        }
        
        /* 大图预览模态框 */
        .modal {
            display: none;
            position: fixed;
            z-index: 100;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.9);
            overflow: auto;
            touch-action: manipulation;
        }
        
        .modal-content {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100%;
            padding: 20px;
        }
        
        .modal-img {
            max-width: 100%;
            max-height: 90vh;
            object-fit: contain;
            -webkit-user-select: none;
            user-select: none;
        }
        
        .close {
            position: absolute;
            top: 15px;
            right: 35px;
            color: #f1f1f1;
            font-size: 40px;
            font-weight: bold;
            cursor: pointer;
        }
        
        /* 加载状态 */
        .loading-text {
            text-align: center;
            color: #999;
            padding: 20px;
            font-size: 14px;
        }
        
        .empty-text {
            text-align: center;
            color: #999;
            padding: 40px 20px;
            font-size: 16px;
        }
        
        /* 响应式调整 */
        @media (max-width: 480px) {
            .header-title {
                font-size: 22px;
            }
            
            .filter-row {
                flex-direction: column;
            }
            
            .filter-group {
                min-width: auto;
                width: 100%;
            }
            
            .detail-grid {
                grid-template-columns: 1fr;
            }
            
            .photo-preview-item {
                width: calc(50% - 8px);
            }
            
            .order-actions {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div class="page-container">
        <!-- <div id="loading">授权检查中...</div> -->
        <div class="header">
            <h1 class="header-title">订单详情🔍</h1>
        </div>
        
        <!-- 下拉选择订单区域 -->
        <div class="dropdown-container">
            <div class="dropdown-header" id="dropdownHeader">
                <div class="dropdown-title">
                    <span class="order-number" id="selectedOrderNumber">请选择订单</span>
                </div>
                <div class="dropdown-arrow">▼</div>
            </div>
            
            <div class="dropdown-list" id="dropdownList">
                <!-- 搜索框 -->
                <div class="search-container">
                    <input type="text" class="search-input" id="searchInput" placeholder="输入公司名称搜索订单...">
                </div>
                
                <div class="order-list" id="orderList">
                    <div class="loading-text">加载中...</div>
                </div>
                <div class="loading-indicator" id="loadingIndicator">正在加载更多...</div>
                <div class="load-more" id="loadMore">加载更多</div>
                <div class="no-more-data" id="noMoreData">没有更多数据了</div>
            </div>
        </div>
        
        <!-- 订单详情 -->
        <div class="order-detail-container" id="orderDetailContainer">
            <div class="loading-text">请先选择订单</div>
        </div>
    </div>

    <!-- 大图预览模态框 -->
    <div id="imageModal" class="modal">
        <span class="close">&times;</span>
        <div class="modal-content">
            <img id="modalImage" class="modal-img">
        </div>
    </div>

    <!-- 引入WeUI JS -->
    <script src="./weui/weui.min.js"></script>
    <script src="./weui/axios.min.js"></script>
    <script src="./axios.js"></script> 
    <script src="./wechat-auth.js"></script>
    <script src="./api.js"></script>
    <script>
        // 存储订单数据
        let allOrders = [];
        let filteredOrders = [];
        let currentOrderDetail = null;
        let currentPage = 1;
        let isLoading = false;
        let hasMore = true;
        let selectedOrder = null;
        let searchKeyword = '';
        let searchTimeout = null;
        let isSearchMode = false; // 新增：标记是否处于搜索模式
        
        // 获取URL参数
        function getUrlParam(name) {
            const urlParams = new URLSearchParams(window.location.search);
            return urlParams.get(name);
        }
        
        // 获取状态对应的CSS类和文本
        function getStatusInfo(status) {
            if (status == 1) {
                return {
                    class: 'status-completed',
                    text: '已完成'
                };
            } else if (status == 2) {
                return {
                    class: 'status-pending',
                    text: '未完成'
                };
            } else {
                return {
                    class: '',
                    text: '未知状态'
                };
            }
        }
        
        // 格式化日期时间
        function formatDateTime(timestamp) {
            if (!timestamp) return '';
            // Unix 时间戳（秒）转换为 JavaScript 时间戳（毫秒）
            const date = new Date(timestamp * 1000);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            
            return `${year}-${month}-${day} ${hours}:${minutes}`;
        }
        
        // 显示大图预览
        function showLargePreview(imageSrc) {
            const modal = document.getElementById('imageModal');
            const modalImg = document.getElementById('modalImage');
            
            modal.style.display = "block";
            modalImg.src = imageSrc;
            
            // 禁用滚动
            document.body.style.overflow = 'hidden';
        }
        
        // 关闭大图预览
        document.querySelector('.close').onclick = function() {
            document.getElementById('imageModal').style.display = "none";
            document.body.style.overflow = 'auto';
        };
        
        // 点击模态框背景关闭
        document.getElementById('imageModal').onclick = function(event) {
            if (event.target === this) {
                this.style.display = "none";
                document.body.style.overflow = 'auto';
            }
        };
        
        // 跳转到终点登记页面
        function goToEndRegistration(orderId) {
            if (!orderId) {
                weui.toast('请先选择订单', {
                    className: 'weui-toast_warn',
                    duration: 2000
                });
                return;
            }
            
            // 跳转到终点登记页面，传递订单ID
            window.location.href = `endWrite.html?order_id=${orderId}`;
        }
        
        // 修改起点订单
        function editStartOrder(orderId) {
            if (!orderId) {
                weui.toast('请先选择订单', {
                    className: 'weui-toast_warn',
                    duration: 2000
                });
                return;
            }
            
            // 跳转到修改起点订单页面，传递订单ID
            window.location.href = `/startWrite.html?order_id=${orderId}`;
        }
        
        // 切换下拉列表显示/隐藏
        function toggleDropdown() {
            const dropdownList = document.getElementById('dropdownList');
            const dropdownArrow = document.querySelector('.dropdown-arrow');
            const dropdownHeader = document.getElementById('dropdownHeader');
            
            if (dropdownList.classList.contains('open')) {
                dropdownList.classList.remove('open');
                dropdownArrow.classList.remove('open');
                dropdownHeader.classList.remove('active');
                
                // 关闭时清空搜索框和搜索状态
                document.getElementById('searchInput').value = '';
                searchKeyword = '';
                isSearchMode = false;
                
            } else {
                dropdownList.classList.add('open');
                dropdownArrow.classList.add('open');
                dropdownHeader.classList.add('active');
                
                // 打开时如果是搜索模式，保持搜索状态；否则加载完整数据
                if (!isSearchMode) {
                    // 重置为显示所有订单
                    loadOrders(1);
                }
                
                // 打开时聚焦搜索框
                setTimeout(() => {
                    document.getElementById('searchInput').focus();
                }, 300);
            }
        }
        
        // 选择订单
        function selectOrder(order,flag=true) {
            selectedOrder = order;
            
            // 更新选中的订单显示
            const selectedOrderNumber = document.getElementById('selectedOrderNumber');
            
            selectedOrderNumber.textContent = order.order_num || order.id;
            if(flag){
            toggleDropdown();
            }
           
            
            // 加载订单详情
            loadOrderDetail(order.id);
            
            // 更新订单列表中的选中状态
            updateOrderListSelection(order.id);
        }
        
        // 更新订单列表中的选中状态
        function updateOrderListSelection(selectedOrderId) {
            const orderItems = document.querySelectorAll('.order-item');
            orderItems.forEach(item => {
                if (item.dataset.id == selectedOrderId) {
                    item.classList.add('active');
                } else {
                    item.classList.remove('active');
                }
            });
        }
        
        // 搜索订单 - 从服务器获取匹配的订单
        async function searchOrders(keyword) {
            searchKeyword = keyword.trim();
            
            if (!searchKeyword) {
                // 如果没有搜索关键词，退出搜索模式，显示所有订单
                isSearchMode = false;
                loadOrders(1);
                return;
            }
            
            isSearchMode = true;
            const orderList = document.getElementById('orderList');
            orderList.innerHTML = '<div class="loading-text">搜索中...</div>';
            
            try {
                // 调用搜索API，传递公司名称作为搜索条件
                const response = await getOrders({
                    openid: localStorage.getItem('wechat_openid'),
                    company: searchKeyword,
                    limit: 20,
                    page: 1
                });
                
                const orders = response.data.data || response.data || response;
                
                if (!orders || orders.length === 0) {
                    orderList.innerHTML = '<div class="empty-text">未找到匹配的订单</div>';
                    return;
                }
                
                // 更新订单列表
                filteredOrders = orders;
                renderOrderList(orders);
                
            } catch (error) {
                console.error('搜索订单失败:', error);
                orderList.innerHTML = '<div class="empty-text" style="color: #f44336;">搜索失败，请重试</div>';
                
                weui.toast('搜索失败', {
                    className: 'weui-toast_warn',
                    duration: 2000
                });
            }
        }
        
        // 渲染订单列表
        function renderOrderList(orders, append = false) {
            const orderList = document.getElementById('orderList');
            const noMoreData = document.getElementById('noMoreData');
            const loadMoreBtn = document.getElementById('loadMore');
            
            if (!orders || orders.length === 0) {
                if (!append) {
                    orderList.innerHTML = '<div class="empty-text">暂无订单数据</div>';
                }
                return;
            }
            
            if (!append) {
                orderList.innerHTML = '';
            }
            
            orders.forEach(order => {
                const statusInfo = getStatusInfo(order.status);
                
                const orderItem = document.createElement('div');
                orderItem.className = 'order-item';
                orderItem.dataset.id = order.id;
                orderItem.dataset.orderNum = order.order_num;
                
                // 如果是当前选中的订单，添加active类
                if (selectedOrder && selectedOrder.id === order.id) {
                    orderItem.classList.add('active');
                }
                
                orderItem.innerHTML = `
                    <div class="order-number">${order.order_num || order.id}</div>
                    <div class="order-meta">
                        <span>${order.company}</span>
                        <span class="order-status ${statusInfo.class}">${statusInfo.text}</span>
                    </div>
                `;
                
                orderItem.addEventListener('click', function() {
                    selectOrder(order);
                });
                
                orderList.appendChild(orderItem);
            });
            
            // 在搜索模式下，隐藏加载更多按钮和没有更多数据提示
            if (isSearchMode) {
                loadMoreBtn.style.display = 'none';
                noMoreData.style.display = 'none';
            } else {
                // 如果没有更多数据且不是搜索状态，显示"没有更多数据了"
                if (!hasMore) {
                    noMoreData.style.display = 'block';
                } else {
                    noMoreData.style.display = 'none';
                }
            }
        }
        
        // 渲染订单详情
        function renderOrderDetail(orderDetail) {
            const orderDetailContainer = document.getElementById('orderDetailContainer');
            
            if (!orderDetail) {
                orderDetailContainer.innerHTML = '<div class="empty-text">暂无订单详情数据</div>';
                return;
            }
            
            const statusInfo = getStatusInfo(orderDetail.status);
            
            // 处理起点图片数据
            let startImagesHtml = '';
            if (orderDetail && orderDetail.images && Array.isArray(orderDetail.images)) {
                startImagesHtml = `
                    <div class="photo-preview-container">
                        ${orderDetail.images.map((imageUrl, index) => `
                            <div class="photo-preview-item">
                                <img src="${imageUrl}" alt="货物照片 ${index + 1}" onclick="showLargePreview('${imageUrl}')">
                            </div>
                        `).join('')}
                    </div>
                `;
            }
            
            // 处理终点图片数据
            let endImagesHtml = '';
            if (orderDetail && orderDetail.pid && orderDetail.pid.images && Array.isArray(orderDetail.pid.images)) {
                endImagesHtml = `
                    <div class="photo-preview-container">
                        ${orderDetail.pid.images.map((imageUrl, index) => `
                            <div class="photo-preview-item">
                                <img src="${imageUrl}" alt="终点货物照片 ${index + 1}" onclick="showLargePreview('${imageUrl}')">
                            </div>
                        `).join('')}
                    </div>
                `;
            }
            
            // 根据状态决定是否显示按钮
            let actionsHtml = '';
            if (orderDetail.status == 2) {
                actionsHtml = `
                    <div class="order-actions">
                        <button class="edit-btn" onclick="editStartOrder('${orderDetail.id}')">修改起点订单</button>
                        <button class="end-btn" onclick="goToEndRegistration('${orderDetail.id}')">去终点记录</button>
                    </div>
                `;
            }
            
            orderDetailContainer.innerHTML = `
                <div class="detail-section">
                    <div class="section-title">基本信息</div>
                    <div class="detail-grid">
                        <div class="detail-item">
                            <span class="detail-label">订单号:</span>
                            <span class="detail-value">${orderDetail.order_num || orderDetail.id || '--'}</span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label">订单状态:</span>
                            <span class="detail-value">
                                <span class="order-status ${statusInfo.class}">
                                    ${statusInfo.text}
                                </span>
                            </span>
                        </div>
                  
                        <div class="detail-item">
                            <span class="detail-label">更新时间:</span>
                            <span class="detail-value">${formatDateTime(orderDetail.updatetime) || '--'}</span>
                        </div>
                    </div>
                </div>
                
                <div class="detail-section">
                    <div class="section-title">起点货物信息</div>
                    <div class="detail-grid">
                        <div class="detail-item">
                            <span class="detail-label">公司名称:</span>
                            <span class="detail-value">${orderDetail.company || '--'}</span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label">货物重量:</span>
                            <span class="detail-value">${orderDetail.heavy ? orderDetail.heavy+'kg' : '--'}</span>
                        </div>
                       
                        
                    </div>
                    ${orderDetail.images && orderDetail.images.length > 0 ? `
                    <div class="section-title" style="margin-top: 15px;">起点货物照片</div>
                    ${startImagesHtml}
                    ` : ''}
                </div>
                
                ${orderDetail.pid && orderDetail.pid ? `
                <div class="detail-section">
                    <div class="section-title">终点货物信息</div>
                    <div class="detail-grid">
                        <div class="detail-item">
                            <span class="detail-label">公司名称:</span>
                            <span class="detail-value">${orderDetail.pid.company || '--'}</span>
                        </div>
                        <div class="detail-item">
                            <span class="detail-label">货物重量:</span>
                            <span class="detail-value">${orderDetail.pid.heavy ? orderDetail.pid.heavy+'kg'  : '--'}</span>
                        </div>
                      
                    </div>
                    ${orderDetail.pid.images && orderDetail.pid.images.length > 0 ? `
                    <div class="section-title" style="margin-top: 15px;">终点货物照片</div>
                    ${endImagesHtml}
                    ` : ''}
                </div>
                ` : ''}
                
                ${actionsHtml}
            `;
            
            currentOrderDetail = orderDetail;
        }
        
        // 加载订单详情
   // 加载订单详情
async function loadOrderDetail(orderId) {
    const orderDetailContainer = document.getElementById('orderDetailContainer');
    const loading = weui.loading('加载订单详情中...');

    try {
        const response = await getOrderDetail({ order_id: orderId , openid: localStorage.getItem('wechat_openid')});
        const orderDetail = response.data || response;
        
        if (!orderDetail) {
            orderDetailContainer.innerHTML = '<div class="empty-text">暂无订单详情数据</div>';
            loading.hide();
            return;
        }
        
        // 渲染订单详情
        renderOrderDetail(orderDetail);
        
        // 更新选中的订单显示为订单号
        const selectedOrderNumber = document.getElementById('selectedOrderNumber');
        selectedOrderNumber.textContent = orderDetail.order_num || orderDetail.id || orderId;
        
        // 设置已选订单信息
        selectedOrder = orderDetail;
        
        loading.hide();
          
    } catch (error) {
        console.error('获取订单详情失败:', error);
        loading.hide();
        
        orderDetailContainer.innerHTML = '<div class="empty-text" style="color: #f44336;">加载失败，请刷新页面</div>';
        weui.toast('订单详情加载失败', {
            className: 'weui-toast_warn',
            duration: 2000
        });
    }
}
        
        // 加载订单列表
 // 加载订单列表
// 加载订单列表
async function loadOrders(page = 1, append = false) {
    if (isLoading) return;
    
    isLoading = true;
    const orderList = document.getElementById('orderList');
    const loadingIndicator = document.getElementById('loadingIndicator');
    const loadMoreBtn = document.getElementById('loadMore');
    const noMoreData = document.getElementById('noMoreData');
    
    if (!append) {
        orderList.innerHTML = '<div class="loading-text">加载中...</div>';
    } else {
        loadingIndicator.style.display = 'block';
    }
    
    let params = {
        openid: localStorage.getItem('wechat_openid'),
        limit: 10,
        page: page
    };
    
    try {
        const response = await getOrders(params);
        const orders = response.data.data || response.data || response;
        
        if (!orders || orders.length === 0) {
            if (!append) {
                orderList.innerHTML = '<div class="empty-text">暂无订单数据</div>';
            }
            hasMore = false;
            loadMoreBtn.style.display = 'none';
            noMoreData.style.display = 'block';
            isLoading = false;
            loadingIndicator.style.display = 'none';
            return;
        }
        
        // 如果是第一页，替换数据；否则追加数据
        if (page === 1) {
            allOrders = orders;
        } else {
            allOrders = [...allOrders, ...orders];
        }
        
        // 初始化过滤订单
        filteredOrders = [...allOrders];
        
        // 渲染订单列表
        renderOrderList(orders, append);
        
        // 只有在没有已选订单时才默认选择第一个
        if (orders.length > 0 && !selectedOrder) {
            selectOrder(orders[0], false);
        }
        
        // 检查是否还有更多数据
        if (orders.length < params.limit) {
            hasMore = false;
            loadMoreBtn.style.display = 'none';
            noMoreData.style.display = 'block';
        } else {
            hasMore = true;
            loadMoreBtn.style.display = 'none'; // 隐藏加载更多按钮，使用滚动加载
            noMoreData.style.display = 'none';
        }
        
        isLoading = false;
        loadingIndicator.style.display = 'none';
        
    } catch (error) {
        console.error('获取订单失败:', error);
        if (!append) {
            orderList.innerHTML = '<div class="empty-text" style="color: #f44336;">加载失败，请刷新页面</div>';
        }
        loadMoreBtn.style.display = 'none';
        isLoading = false;
        loadingIndicator.style.display = 'none';
        
        weui.toast('订单加载失败', {
            className: 'weui-toast_warn',
            duration: 2000
        });
    }
}
        
        // 滚动加载更多
        function handleScrollLoad() {
            const dropdownList = document.getElementById('dropdownList');
            const loadingIndicator = document.getElementById('loadingIndicator');
            
            // 在搜索模式下不进行滚动加载
            if (isSearchMode) return;
            
            // 检查是否滚动到底部
            if (dropdownList.scrollTop + dropdownList.clientHeight >= dropdownList.scrollHeight - 50) {
                if (hasMore && !isLoading) {
                    currentPage++;
                    loadOrders(currentPage, true);
                }
            }
        }
        
        // 页面加载完成后执行
      // 页面加载完成后执行
// 页面加载完成后执行
// 页面加载完成后执行
// 页面加载完成后执行
// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', async function() {
    try {
        const urlOrderId = getUrlParam('order_id');
        
        // 确保下拉列表初始状态为关闭
        const dropdownList = document.getElementById('dropdownList');
        const dropdownArrow = document.querySelector('.dropdown-arrow');
        const dropdownHeader = document.getElementById('dropdownHeader');
        
        // 显式设置关闭状态
        dropdownList.classList.remove('open');
        dropdownArrow.classList.remove('open');
        dropdownHeader.classList.remove('active');
        
        // 如果有URL参数，立即加载详情
        if (urlOrderId) {
            document.getElementById('selectedOrderNumber').textContent = `订单ID: ${urlOrderId}`;
            await loadOrderDetail(urlOrderId);
        }
        
        // 加载订单列表
        await loadOrders(1);
        
        // 如果URL参数存在，在订单列表加载完成后更新显示
        if (urlOrderId) {
            const targetOrder = allOrders.find(order => order.id === urlOrderId);
            if (targetOrder) {
                document.getElementById('selectedOrderNumber').textContent = targetOrder.order_num || targetOrder.id;
                selectedOrder = targetOrder;
                updateOrderListSelection(urlOrderId);
            }
        }
        
        // 事件监听器
        document.getElementById('dropdownHeader').addEventListener('click', toggleDropdown);
        
        document.getElementById('searchInput').addEventListener('input', function(e) {
            const keyword = e.target.value;
            if (searchTimeout) clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => searchOrders(keyword), 500);
        });
        
        document.getElementById('searchInput').addEventListener('click', function(e) {
            e.stopPropagation();
        });
        
        document.getElementById('dropdownList').addEventListener('scroll', handleScrollLoad);
        
        document.addEventListener('click', function(event) {
            const dropdownContainer = document.querySelector('.dropdown-container');
            const dropdownList = document.getElementById('dropdownList');
            if (!dropdownContainer.contains(event.target) && dropdownList.classList.contains('open')) {
                toggleDropdown();
            }
        });
        
    } catch (error) {
        console.error('页面初始化失败:', error);
        document.getElementById('loading').innerHTML = '加载失败，请刷新页面';
    }
});
    </script>
</body>
</html>